package com.authentications.security.handler;

import com.alibaba.fastjson.JSONObject;
import com.authentications.utils.JwtSpringSecurityTokenUtils;
import com.authentications.utils.ResultBean;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * @ClassName JWTAuthenticationFilter
 * @Author xiezhuocai
 * @Description 通过过滤器去认证登录
 * @Date 2021/12/20 10:23
 */
public class JwtAuthenticationFilter extends UsernamePasswordAuthenticationFilter {

    private AuthenticationManager authenticationManager;

    private JwtSpringSecurityTokenUtils tokenUtils;

    public JwtAuthenticationFilter(AuthenticationManager authenticationManager,
                                   JwtSpringSecurityTokenUtils tokenUtils) {
        this.authenticationManager = authenticationManager;
        this.tokenUtils = tokenUtils;
        super.setFilterProcessesUrl("/login");
    }

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request,
                                                HttpServletResponse response) throws AuthenticationException {

        // 前端传过来的是json数据
        /*try {
            LoginUser loginUser = new ObjectMapper().readValue(request.getInputStream(), LoginUser.class);
            rememberMe.set(loginUser.getRememberMe() == null ? 0 : loginUser.getRememberMe());
            return authenticationManager.authenticate(
                    new UsernamePasswordAuthenticationToken(loginUser.getUsername(), loginUser.getPassword(), new ArrayList<>())
            );
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }*/
        // 前端传过来的是key-value数据
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        /*LoginUser loginUser=new LoginUser(username,password);
        rememberMe.set(loginUser.getRememberMe() == null ? 0 : loginUser.getRememberMe());*/
        return authenticationManager.authenticate(
                new UsernamePasswordAuthenticationToken(request.getParameter("username"), request.getParameter(
                        "password"), new ArrayList<>()));
    }

    // 成功验证后调用的方法
    // 如果验证成功，就生成token并返回
    @Override
    protected void successfulAuthentication(HttpServletRequest request,
                                            HttpServletResponse response,
                                            FilterChain chain,
                                            Authentication authResult) throws IOException, ServletException {

        UserDetails jwtUser = (UserDetails) authResult.getPrincipal();

        List<String> role = new ArrayList();
        Collection<? extends GrantedAuthority> authorities = jwtUser.getAuthorities();
        for (GrantedAuthority authority : authorities){
            role.add(authority.getAuthority());
        }


        String token = tokenUtils.createToken(jwtUser.getUsername(), role, true);
        //String token = JwtTokenUtils.createToken(jwtUser.getUsername(), false);
        // 返回创建成功的token
        // 但是这里创建的token只是单纯的token
        // 按照jwt的规定，最后请求的时候应该是 `Bearer token`
        //response.setHeader("Authorization", tokenUtils.TOKEN_PREFIX + token);
        PrintWriter writer = response.getWriter();
        writer.print(JSONObject.toJSONString(ResultBean.succeed(JwtSpringSecurityTokenUtils.TOKEN_PREFIX + token)));
        writer.close();
        response.flushBuffer();
    }

    @Override
    protected void unsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response, AuthenticationException failed) throws IOException, ServletException {
        response.setCharacterEncoding("utf-8");
        PrintWriter writer = response.getWriter();
        writer.print(JSONObject.toJSONString(ResultBean.defaultError(failed.getMessage())));
        writer.close();
        response.flushBuffer();
        //response.getWriter().write("authentication failed, reason: " + failed.getMessage());
    }

}
